import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_datetime_picker/flutter_datetime_picker.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_easyrefresh/material_footer.dart';
import 'package:flutter_easyrefresh/material_header.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:panda/base/Constant.dart';
import 'package:panda/base/SignType.dart';
import 'package:panda/entity/address_entity.dart';
import 'package:panda/http/Api.dart';
import 'package:panda/http/HttpUtil.dart';
import 'package:panda/util/AppSaveInfoUtil.dart';
import 'package:panda/util/DateUtils.dart';
import 'package:panda/util/SignUtil.dart';

class YeJiChildPage extends StatefulWidget {
  int type;
  YeJiChildPage({Key key, @required this.type}) : super(key: key);

  @override
  _YeJiChildPageState createState() => _YeJiChildPageState();
}

class _YeJiChildPageState extends State<YeJiChildPage>
    with AutomaticKeepAliveClientMixin {
  int page = 1;
  String time1 = "全部日期", time2 = "全部日期", token = "", one = "0", two = "0";
  // List<AddressListDataData> dataList = new List();
  EasyRefreshController _controller = EasyRefreshController();
  List<String> list1 = new List();
  List<String> list2 = new List();
  List<String> list77 = new List();

  List<String> list3 = new List();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    var today = DateTime.now();
    // time1 = DateUtils.instance.getFormartData(
    //     timeSamp: today.millisecondsSinceEpoch, format: "yyyy-MM-dd");
    // time2 = time1;
    setState(() {});
    getString(TOKEN).then((value) {
      token = value;
      print(token);
      loadList();
    });
  }

  loadList() async {
    Map map = new Map();
    map['token'] = token;
    map['p'] = page.toString();
    map['per'] = "10";
    map['type'] = widget.type;
    if (!time1.contains("全部")) {
      map['start'] = time1;
      map['end'] = time2;
    } else {
      map['start'] = "2019-10-10";
      map['end'] = "2059-10-10";
    }
    map['sign_type'] =
        widget.type == 3 ? SignType.GET_BONUSLIST : SignType.GET_ARCHIEVEMENT;
    Response<String> response = await HttpUtil().post(
        widget.type == 3 ? Api.GET_BONUSLIST : Api.GET_ACHIEVEMENT,
        data: getSign(map));
    Map userMap = json.decode(response.data);
    if (userMap['code'] != 1) {
      Fluttertoast.showToast(msg: userMap['msg']);
      return;
    }
    // AddressListEntity homeListEntity = new AddressListEntity.fromJson(userMap);
    if (mounted)
      setState(() {
        one = userMap['data']['allprice'].toString();
        two = userMap['data']['total'].toString();
        if (page == 1) {
          // dataList.clear();
          list1.clear();
          list3.clear();
          list77.clear();
          list2.clear();
          (userMap['data']['list'] as List).forEach((v) {
            list1.add(widget.type == 2
                ? v['title'].toString()
                : v['create_time'].toString());
            list77.add(v['create_time'].toString());
            list2.add(widget.type == 3
                ? v['check_zh'].toString()
                : v['num'].toString());
            list3.add(widget.type == 3
                ? v['money'].toString()
                : v['allprice'].toString());
          });
          _controller.finishRefresh();
          _controller.resetLoadState();
          // dataList.addAll(homeListEntity.data.datas);
        } else {
          (userMap['data']['list'] as List).forEach((v) {
            list1.add(widget.type == 2
                ? v['title'].toString()
                : v['create_time'].toString());
            list2.add(widget.type == 3
                ? v['check_zh'].toString()
                : v['num'].toString());
            list3.add(widget.type == 3
                ? v['money'].toString()
                : v['allprice'].toString());
                list77.add(v['create_time'].toString());
          });
          _controller.finishLoad(
              noMore: (userMap['data']['list'] as List).length == 0);
        }
      });
  }

  @override
  Widget build(BuildContext context) {
    return Column(children: <Widget>[
      Container(
          color: Colors.grey[100],
          padding: EdgeInsets.all(20),
          child: Row(children: <Widget>[
            Expanded(child: Center()),
            GestureDetector(
              child: Container(
                padding: EdgeInsets.fromLTRB(20, 3, 10, 3),
                decoration: BoxDecoration(
                    border: Border.all(color: mainColor, width: 1),
                    borderRadius: BorderRadius.circular(3)),
                child: Row(children: <Widget>[
                  Text('$time1',
                      style: TextStyle(
                          color: mainColor,
                          fontSize:
                              ScreenUtil.getInstance().setSp(SMALL_FONT_SIZE))),
                  Icon(
                    Icons.arrow_drop_down,
                    color: mainColor,
                  )
                ]),
              ),
              onTap: () {
                DatePicker.showDatePicker(context,
                    showTitleActions: true,
                    onChanged: (date) {}, onConfirm: (date) {
                  setState(() {
                    time1 = DateUtils.instance.getFormartData(
                        timeSamp: date.millisecondsSinceEpoch,
                        format: "yyyy-MM-dd");
                  });
                  page = 1;
                  loadList();
                }, currentTime: DateTime.now(), locale: LocaleType.zh);
              },
            ),
            Expanded(
              child: Center(
                  child: Text('至',
                      style: TextStyle(
                          color: black,
                          fontSize: ScreenUtil.getInstance()
                              .setSp(SMALL_FONT_SIZE)))),
            ),
            GestureDetector(
              child: Container(
                padding: EdgeInsets.fromLTRB(20, 3, 10, 3),
                decoration: BoxDecoration(
                    border: Border.all(color: mainColor, width: 1),
                    borderRadius: BorderRadius.circular(3)),
                child: Row(children: <Widget>[
                  Text('$time2',
                      style: TextStyle(
                          color: mainColor,
                          fontSize:
                              ScreenUtil.getInstance().setSp(SMALL_FONT_SIZE))),
                  Icon(
                    Icons.arrow_drop_down,
                    color: mainColor,
                  )
                ]),
              ),
              onTap: () {
                DatePicker.showDatePicker(context,
                    showTitleActions: true,
                    onChanged: (date) {}, onConfirm: (date) {
                  setState(() {
                    time2 = DateUtils.instance.getFormartData(
                        timeSamp: date.millisecondsSinceEpoch,
                        format: "yyyy-MM-dd");
                  });
                  page = 1;
                  loadList();
                }, currentTime: DateTime.now(), locale: LocaleType.zh);
              },
            ),
            Expanded(child: Center()),
          ])),
      Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Expanded(child: Center()),
          Container(
              child: Column(
                children: <Widget>[
                  Text(
                      widget.type == 3
                          ? '个人总分红(元)'
                          : widget.type == 1 ? '个人总业绩(元)' : '团队总业绩(元',
                      style: TextStyle(
                          color: Colors.black54,
                          fontSize: ScreenUtil.getInstance()
                              .setSp(NORMAL_FONT_SIZE))),
                  Container(
                    height: 5,
                  ),
                  Text('$one',
                      style: TextStyle(
                          color: mainColor,
                          fontSize: ScreenUtil.getInstance()
                              .setSp(NORMAL_FONT_SIZE * 2 - 10))),
                ],
              ),
              padding: EdgeInsets.fromLTRB(40, 20, 40, 20),
              decoration: BoxDecoration(
                  color: white, borderRadius: BorderRadius.circular(4))),
          Expanded(child: Center()),
          Offstage(
            offstage: widget.type == 3,
            child: Container(
                child: Column(
                  children: <Widget>[
                    Text(widget.type == 1 ? '个人总单数(单)' : '团队总单数(单)',
                        style: TextStyle(
                            color: Colors.black54,
                            fontSize: ScreenUtil.getInstance()
                                .setSp(NORMAL_FONT_SIZE))),
                    Container(
                      height: 5,
                    ),
                    Text('$two',
                        style: TextStyle(
                            color: black,
                            fontSize: ScreenUtil.getInstance()
                                .setSp(NORMAL_FONT_SIZE * 2 - 10))),
                  ],
                ),
                padding: EdgeInsets.fromLTRB(40, 20, 40, 20),
                decoration: BoxDecoration(
                    color: white, borderRadius: BorderRadius.circular(4))),
          ),
          Expanded(child: Center(), flex: widget.type == 3 ? 0 : 1),
        ],
      ),
      Expanded(
          child: Container(
        color: white,
        padding: EdgeInsets.all(15),
        width: double.infinity,
        margin: EdgeInsets.only(top: 15),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Text(
              widget.type == 1
                  ? "个人业绩明细"
                  : widget.type == 2 ? '团队业绩明细' : '全民分红明细',
              style: TextStyle(
                  color: Colors.black87,
                  fontSize: ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE)),
            ),
            Container(
              width: double.infinity,
              height: 1,
              color: f0Color,
              margin: EdgeInsets.only(top: 10, bottom: 10),
            ),
            Padding(
              padding: EdgeInsets.only(
                  left: ScreenUtil.getInstance().setHeight(0),
                  right: ScreenUtil.getInstance().setHeight(0)),
              child: Row(
                children: <Widget>[
                  Container(
                    alignment: Alignment.center,
                    width: (MediaQuery.of(context).size.width - 30)*2 / 4,
                    child: Text(widget.type == 2 ? '人员' : '日期',
                        style: TextStyle(
                            color: Colors.black87,
                            fontSize: ScreenUtil.getInstance()
                                .setSp(SMALL_FONT_SIZE))),
                  ),
                  Container(
                    alignment: Alignment.center,
                    width: (MediaQuery.of(context).size.width - 30) / 4,
                    child: Text(widget.type == 3 ? '达标(单)' : '单数(单)',
                        style: TextStyle(
                            color: Colors.black87,
                            fontSize: ScreenUtil.getInstance()
                                .setSp(SMALL_FONT_SIZE))),
                  ),
                  Container(
                    alignment: Alignment.center,
                    width: (MediaQuery.of(context).size.width - 30) / 4,
                    child: Text(widget.type == 3 ? '分红(元)' : '业绩(元)',
                        style: TextStyle(
                            color: Colors.black87,
                            fontSize: ScreenUtil.getInstance()
                                .setSp(SMALL_FONT_SIZE))),
                  ),
                ],
              ),
            ),
            Container(
              color: white,
              height: 18,
            ),
            Expanded(
                child: new EasyRefresh(
              enableControlFinishRefresh: true,
              enableControlFinishLoad: true,
              header: MaterialHeader(),
              footer: MaterialFooter(),
              controller: _controller,
              child: ListView.separated(
                  itemBuilder: _renderRow,
                  separatorBuilder: (BuildContext context, int index) {
                    return Container(
                      color: f0Color,
                      height: 1,
                    );
                  },
                  itemCount: list1.length),
              onRefresh: () async {
                page = 1;
                loadList();
              },
              onLoad: () async {
                page++;
                loadList();
              },
            ))
          ],
        ),
      ))
    ]);
  }

  Widget _renderRow(BuildContext context, int index) {
    return Container(
      padding: EdgeInsets.only(top: 4, bottom: 5),
      child: Row(
        children: <Widget>[
          Container(
            alignment: Alignment.center,
            width: (MediaQuery.of(context).size.width - 30) *2/ 4,
            child: Text(list1[index]+ (widget.type == 1?"":"\n"+list77[index]),
            textAlign: TextAlign.center,
                style: TextStyle(
                    color: Colors.black38,
                    fontSize:
                        ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE))),
          ),
          Container(
            alignment: Alignment.center,
            width: (MediaQuery.of(context).size.width - 30) / 4,
            child: Text(list2[index],
                style: TextStyle(
                    color: Colors.black54,
                    fontSize:
                        ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE))),
          ),
          Container(
            alignment: Alignment.center,
            width: (MediaQuery.of(context).size.width - 30) / 4,
            child: Text(list3[index],
                style: TextStyle(
                    color: mainColor,
                    fontSize:
                        ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE))),
          ),
        ],
      ),
    );
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}
